# backend/app/routers/auth.py
from datetime import timedelta, datetime
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.database import get_db
from app.models.user import User, UserStatus, UserRole
from app.schemas.auth import Token, LoginRequest
from app.schemas.user import UserCreate
from app.auth import verify_password, get_password_hash, create_access_token, get_current_active_user
from app.services.user_service import UserService

router = APIRouter()

@router.post("/login", response_model=Token)
async def login(
    login_data: LoginRequest,
    db: Session = Depends(get_db)
):
    """用户登录"""
    user = db.query(User).filter(
        User.username == login_data.username, 
        User.is_deleted == False
    ).first()
    
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    if user.status != UserStatus.ACTIVE:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户账户未激活"
        )
    
    if not verify_password(login_data.password, user.hashed_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    # 更新最后登录时间
    user.last_login = datetime.utcnow()
    db.commit()
    
    access_token = create_access_token(data={"sub": user.username})
    
    return {
        "access_token": access_token,
        "token_type": "bearer",
        "user": {
            "id": user.id,
            "username": user.username,
            "email": user.email,
            "full_name": user.full_name,
            "role": user.role.value,
            "avatar": user.avatar
        }
    }

@router.post("/register")
async def register(
    user_data: UserCreate,
    db: Session = Depends(get_db)
):
    """用户注册"""
    try:
        # 创建用户（UserService 内部处理重复检查）
        user_service = UserService(db)
        created_user = user_service.create_user(user_data)
        
        return {
            "message": "注册成功", 
            "user": {
                "id": created_user.id,
                "username": created_user.username,
                "email": created_user.email,
                "full_name": created_user.full_name,
                "role": created_user.role.value
            }
        }
    except HTTPException:
        # 重新抛出已知异常
        raise
    except Exception as e:
        # 捕获其他数据库错误
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="注册失败: " + str(e)
        )

@router.post("/logout")
async def logout():
    """用户登出"""
    return {"message": "登出成功"}

@router.post("/change-password")
async def change_password(
    password_data: dict,
    current_user: User = Depends(get_current_active_user)
):
    """修改密码"""
    if not password_data.get("old_password") or not password_data.get("new_password"):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="请提供旧密码和新密码"
        )
    
    # 验证旧密码
    if not verify_password(password_data["old_password"], current_user.hashed_password):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="旧密码错误"
        )
    
    # 更新密码
    current_user.hashed_password = get_password_hash(password_data["new_password"])
    current_user.updated_at = datetime.utcnow()
    db.commit()
    
    return {"message": "密码修改成功"}

@router.get("/me")
async def get_current_user_info(
    current_user: User = Depends(get_current_active_user)
):
    """获取当前用户信息"""
    return {
        "id": current_user.id,
        "username": current_user.username,
        "email": current_user.email,
        "full_name": current_user.full_name,
        "role": current_user.role.value,
        "avatar": current_user.avatar,
        "created_at": current_user.created_at,
        "last_login": current_user.last_login
    }